import React, { useState, useEffect } from 'react'
import { Plus, Edit2, Trash2, Save, X, FileText, Calendar, ArrowLeft } from 'lucide-react'
import * as XLSX from 'xlsx'
import { equipmentMaintenanceAPI, API_BASE_URL } from '../services/api'
import ImageUpload from './ImageUpload'

// 自定义滚动条样式
const scrollbarStyles = `
  .repair-history-scroll::-webkit-scrollbar {
    width: 8px;
  }
  .repair-history-scroll::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  .repair-history-scroll::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
  .repair-history-scroll::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  .maintenance-history-scroll::-webkit-scrollbar {
    width: 8px;
  }
  .maintenance-history-scroll::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
  }
  .maintenance-history-scroll::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
  }
  .maintenance-history-scroll::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
`

// 添加样式到页面
if (typeof document !== 'undefined') {
  const styleElement = document.createElement('style')
  styleElement.textContent = scrollbarStyles
  if (!document.head.querySelector('style[data-repair-scroll]')) {
    styleElement.setAttribute('data-repair-scroll', 'true')
    document.head.appendChild(styleElement)
  }
}

const EquipmentMaintenance = () => {
  // 界面状态 - 从localStorage读取上次的视图状态
  const [currentView, setCurrentView] = useState(() => {
    return localStorage.getItem('equipmentMaintenanceView') || 'main'
  }) // 'main', 'maintenance', 'repair'
  
  // 当currentView改变时，保存到localStorage
  useEffect(() => {
    localStorage.setItem('equipmentMaintenanceView', currentView)
  }, [currentView])
  
  // 维修记录数据
  const [repairRecords, setRepairRecords] = useState([])
  
  // 维保记录数据
  const [maintenanceRecords, setMaintenanceRecords] = useState([])
  
  // ImageUpload组件引用
  const imageUploadRef = React.useRef()

  // 维修记录单表单数据
  const [repairFormData, setRepairFormData] = useState({
    recordNumber: '',
    systemName: '',
    equipmentName: '',
    faultDate: '',
    equipmentNumber: '',
    faultDescription: '',
    maintainerName: '',
    contactPhone: '',
    maintenanceMethod: '',
    replacementParts: '',
    completionDate: '',
    confirmer: '',
    attachments: ''
  })

  // 维修记录单编辑状态管理
  const [editingRepairRecordId, setEditingRepairRecordId] = useState(null)
  const [editingRepairData, setEditingRepairData] = useState({})
  
  // 查看维修记录单表格状态管理
  const [viewingRecordId, setViewingRecordId] = useState(null)
  
  // 新建表单显示状态
  const [showNewRecordForm, setShowNewRecordForm] = useState(false)
  
  // 图片管理状态
  const [repairRecordImages, setRepairRecordImages] = useState({})
  
  // 从后端API加载维修记录数据
  const loadRepairRecords = async () => {
    try {
      let allResults = []
      let nextUrl = '/equipment-maintenance/repair-records/'
      
      while (nextUrl) {
        const data = await equipmentMaintenanceAPI.repairRecords.getAll(nextUrl)
        allResults = allResults.concat(data.results)
        
        if (data.next && typeof data.next === 'string') {
          try {
            const url = new URL(data.next)
            nextUrl = url.pathname.replace('/api', '') + url.search
          } catch (error) {
            console.error('Invalid URL:', data.next, error)
            nextUrl = null
          }
        } else {
          nextUrl = null
        }
      }
      
      // 转换数据格式以匹配前端状态
      const formattedRecords = allResults.map(record => ({
        id: record.id,
        recordNumber: record.record_number,
        systemName: record.system_name,
        equipmentName: record.equipment_name,
        faultDate: record.fault_date,
        equipmentNumber: record.equipment_number,
        faultDescription: record.fault_description,
        maintainerName: record.maintainer_name,
        contactPhone: record.contact_phone,
        maintenanceMethod: record.maintenance_method,
        replacementParts: record.replacement_parts,
        completionDate: record.completion_date,
        confirmer: record.confirmer,
        attachments: record.attachments,
        createTime: record.created_at,
        updateTime: record.updated_at
      }))
      
      setRepairRecords(formattedRecords)
      
      // 加载每个维修记录的图片数据
      const imagePromises = formattedRecords.map(async (record) => {
        try {
          const response = await equipmentMaintenanceAPI.repairRecordImages.getAll(record.id)
          // API返回的是分页数据结构，需要取results字段
          const images = response?.results || []
          return { recordId: record.id, images: images }
        } catch (error) {
          console.error(`加载维修记录 ${record.id} 的图片失败:`, error)
          return { recordId: record.id, images: [] }
        }
      })
      
      const imageResults = await Promise.all(imagePromises)
      const imageMap = {}
      imageResults.forEach(result => {
        imageMap[result.recordId] = result.images
      })
      
      setRepairRecordImages(imageMap)
    } catch (error) {
      console.error('加载维修记录失败:', error)
    }
  }

  // 维保记录表管理
  const [maintenanceTableRecords, setMaintenanceTableRecords] = useState([])
  
  // 从后端API加载维保记录数据
  const loadMaintenanceRecords = async () => {
    try {
      // 获取所有分页数据
      let allResults = []
      let nextUrl = '/equipment-maintenance/maintenance-items/'
      
      while (nextUrl) {
        const data = await equipmentMaintenanceAPI.maintenanceItems.getAll(nextUrl)
        allResults = allResults.concat(data.results)
        
        // 检查是否有下一页，提取相对路径
        if (data.next && typeof data.next === 'string') {
          try {
            const url = new URL(data.next)
            // 移除 /api 前缀，只保留相对路径
            nextUrl = url.pathname.replace('/api', '') + url.search
          } catch (error) {
            console.error('Invalid URL:', data.next, error)
            nextUrl = null
          }
        } else {
          nextUrl = null
        }
      }
      
      // 将后端数据转换为前端期望的格式
      const groupedRecords = {}
      
      allResults.forEach(item => {
          const key = `${item.system_name}_${item.system_category}`
          
          if (!groupedRecords[key]) {
            groupedRecords[key] = {
              id: key, // 使用系统名称和分类作为唯一标识
              systemName: item.system_name,
              systemCategory: item.system_category,
              equipments: {},
              createTime: item.create_time || new Date().toLocaleString()
            }
          }
          
          if (!groupedRecords[key].equipments[item.equipment_name]) {
            groupedRecords[key].equipments[item.equipment_name] = {
              id: `${key}_${item.equipment_name}`, // 使用组合键作为设备ID
              name: item.equipment_name,
              maintenanceItems: []
            }
          }
          
          groupedRecords[key].equipments[item.equipment_name].maintenanceItems.push({
            id: item.id, // 保留后端的真实ID
            content: item.content,
            level: item.level,
            cycle: item.cycle,
            type: item.type,
            months: item.months || {
              '1月': false,
              '2月': false,
              '3月': false,
              '4月': false,
              '5月': false,
              '6月': false,
              '7月': false,
              '8月': false,
              '9月': false,
              '10月': false,
              '11月': false,
              '12月': false
            }
          })
        })
        
        // 转换为数组格式
        const records = Object.values(groupedRecords).map(record => ({
          ...record,
          equipments: Object.values(record.equipments)
        }))
        
        setMaintenanceTableRecords(records)
    } catch (error) {
      console.error('加载维保记录失败:', error)
      // 如果API调用失败，尝试从localStorage加载
      const saved = localStorage.getItem('experimentSystem_maintenanceTableRecords')
      if (saved) {
        setMaintenanceTableRecords(JSON.parse(saved))
      }
    }
  }
  
  // 维保记录表单数据 - 新的树形结构
  const [maintenanceFormData, setMaintenanceFormData] = useState({
    systemName: '',
    equipments: [] // 设备列表，每个设备包含多个维保内容
  })
  
  // 右键菜单状态
  const [contextMenu, setContextMenu] = useState({
    visible: false,
    x: 0,
    y: 0,
    type: '', // 'equipment' 或 'maintenance'
    equipmentId: null,
    maintenanceId: null
  })
  
  // 选中的设备和维保内容
  const [selectedEquipment, setSelectedEquipment] = useState(null)
  const [selectedMaintenance, setSelectedMaintenance] = useState(null)
  
  // 维保记录表界面状态
  const [showMaintenanceForm, setShowMaintenanceForm] = useState(false)
  const [editingMaintenanceId, setEditingMaintenanceId] = useState(null)
  const [maintenanceSearchTerm, setMaintenanceSearchTerm] = useState('')
  const [rowCount, setRowCount] = useState(20)
  
  // 当前选中的系统，默认显示真空热试验系统
  const [selectedSystem, setSelectedSystem] = useState('真空热试验系统维护保养记录表')

  // 组件加载时从后端获取数据
  useEffect(() => {
    loadMaintenanceRecords()
    loadRepairRecords()
  }, [])

  // 点击页面其他地方隐藏右键菜单
  useEffect(() => {
    const handleClickOutside = (e) => {
      if (contextMenu.visible) {
        hideContextMenu()
      }
    }
    document.addEventListener('click', handleClickOutside)
    return () => document.removeEventListener('click', handleClickOutside)
  }, [contextMenu.visible])

  // 生成记录编号
  const generateRecordNumber = () => {
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const sequence = String(repairRecords.length + 1).padStart(3, '0')
    return `${year}${month}${day}${sequence}`
  }

  // 重置维修记录表单
  const resetRepairForm = () => {
    setRepairFormData({
      recordNumber: '',
      systemName: '',
      equipmentName: '',
      faultDate: '',
      equipmentNumber: '',
      faultDescription: '',
      maintainerName: '',
      contactPhone: '',
      maintenanceMethod: '',
      replacementParts: '',
      completionDate: '',
      confirmer: '',
      attachments: ''
    })
    // 清除编辑状态
    setEditingRepairRecordId(null)
    setEditingRepairData({})
    // 清除查看状态
    setViewingRecordId(null)
  }

  // 保存维修记录
  const saveRepairRecord = async () => {
    if (!repairFormData.systemName || !repairFormData.equipmentName) {
      alert('请填写系统名称和设备名称')
      return
    }

    try {
      if (editingRepairRecordId) {
        // 编辑模式：更新现有记录
        const updatedData = {
          record_number: repairFormData.recordNumber,
          system_name: repairFormData.systemName,
          equipment_name: repairFormData.equipmentName,
          fault_date: repairFormData.faultDate,
          equipment_number: repairFormData.equipmentNumber,
          fault_description: repairFormData.faultDescription,
          maintainer_name: repairFormData.maintainerName,
          contact_phone: repairFormData.contactPhone,
          maintenance_method: repairFormData.maintenanceMethod,
          replacement_parts: repairFormData.replacementParts,
          completion_date: repairFormData.completionDate,
          confirmer: repairFormData.confirmer,
          attachments: repairFormData.attachments
        }
        
        await equipmentMaintenanceAPI.repairRecords.update(editingRepairRecordId, updatedData)
        
        // 更新本地状态
        setRepairRecords(prev => 
          prev.map(record => 
            record.id === editingRepairRecordId 
              ? { ...record, ...repairFormData, updateTime: new Date().toLocaleString() }
              : record
          )
        )
        setEditingRepairRecordId(null)
        setEditingRepairData({})
        // 维修记录修改成功
      } else {
        // 新建模式：创建新记录
        const newRecordData = {
          record_number: repairFormData.recordNumber,
          system_name: repairFormData.systemName,
          equipment_name: repairFormData.equipmentName,
          fault_date: repairFormData.faultDate,
          equipment_number: repairFormData.equipmentNumber,
          fault_description: repairFormData.faultDescription,
          maintainer_name: repairFormData.maintainerName,
          contact_phone: repairFormData.contactPhone,
          maintenance_method: repairFormData.maintenanceMethod,
          replacement_parts: repairFormData.replacementParts,
          completion_date: repairFormData.completionDate,
          confirmer: repairFormData.confirmer,
          attachments: repairFormData.attachments
        }
        
        const response = await equipmentMaintenanceAPI.repairRecords.create(newRecordData)
        
        // 更新本地状态，使用服务器返回的ID
        const newRecord = {
          id: response.id,
          ...repairFormData,
          createTime: new Date().toLocaleString()
        }
        
        setRepairRecords(prev => [...prev, newRecord])
        
        // 更新表单数据中的ID，以便图片上传
        setRepairFormData(prev => ({ ...prev, id: response.id }))
        
        // 上传临时文件
        if (imageUploadRef.current && imageUploadRef.current.uploadTempFiles) {
          await imageUploadRef.current.uploadTempFiles(response.id)
        }
        
        // 维修记录保存成功
        // 关闭新建表单
        setShowNewRecordForm(false)
        return // 不重置表单，让用户可以继续上传图片
      }
    } catch (error) {
      console.error('保存维修记录失败:', error)
      alert('保存失败，请重试')
      return
    }
    
    resetRepairForm()
  }

  // 删除维修记录
  const deleteRepairRecord = async (recordId) => {
    if (window.confirm('确定要删除这条维修记录吗？')) {
      try {
        // 调用后端API删除记录
        await equipmentMaintenanceAPI.repairRecords.delete(recordId)
        
        // 从前端状态中移除记录
        setRepairRecords(prev => prev.filter(record => record.id !== recordId))
        alert('维修记录删除成功')
      } catch (error) {
        console.error('删除维修记录失败:', error)
        alert(`删除失败: ${error.message}`)
      }
    }
  }

  // 处理Word文档导入
  const handleWordImport = async (event) => {
    const file = event.target.files[0]
    if (!file) return

    if (!file.name.toLowerCase().endsWith('.docx') && !file.name.toLowerCase().endsWith('.doc')) {
      alert('请选择Word文档文件（.doc或.docx格式）')
      return
    }

    const formData = new FormData()
    formData.append('file', file)

    try {
      const result = await equipmentMaintenanceAPI.repairRecords.importWord(formData)
      if (result.created_records && result.created_records.length > 0) {
          // 将导入的记录添加到现有记录中，转换字段名从snake_case到camelCase
          const newRecords = result.created_records.map(record => ({
            id: record.id || Date.now() + Math.random(), // 使用后端ID或生成临时ID
            recordNumber: record.record_number,
            systemName: record.system_name,
            equipmentName: record.equipment_name,
            faultDate: record.fault_date,
            equipmentNumber: record.equipment_number,
            faultDescription: record.fault_description,
            maintainerName: record.maintainer_name,
            contactPhone: record.contact_phone,
            maintenanceMethod: record.maintenance_method,
            replacementParts: record.replacement_parts,
            completionDate: record.completion_date,
            confirmer: record.confirmer,
            attachments: record.attachments,
            createTime: record.create_time,
            updateTime: record.update_time
          }))
          setRepairRecords(prev => [...prev, ...newRecords])
          alert(`成功导入 ${result.created_records.length} 条维修记录`)
        } else {
          alert('Word文档中未找到有效的维修记录数据')
        }
    } catch (error) {
      console.error('导入Word文档失败:', error)
      alert(`导入失败: ${error.message}`)
    }

    // 清空文件输入
    event.target.value = ''
  }

  // 处理新建记录
  const handleCreateNewRecord = () => {
    // 重置表单
    resetRepairForm()
    // 新建记录时No编号默认为空白
    setRepairFormData(prev => ({
      ...prev,
      recordNumber: ''
    }))
    // 清除编辑状态
    setEditingRepairRecordId(null)
    setEditingRepairData({})
    // 清除查看状态
    setViewingRecordId(null)
    // 显示新建表单
    setShowNewRecordForm(true)
  }

  // 开始编辑维修记录
  const startEditRecord = (record) => {
    setEditingRepairRecordId(record.id)
    setEditingRepairData({ ...record })
    // 清除查看状态，确保不会同时显示两个表单
    setViewingRecordId(null)
    // 将记录数据填充到表单中
    setRepairFormData({
      recordNumber: record.recordNumber,
      systemName: record.systemName,
      equipmentName: record.equipmentName,
      faultDate: record.faultDate,
      equipmentNumber: record.equipmentNumber,
      faultDescription: record.faultDescription,
      maintainerName: record.maintainerName,
      contactPhone: record.contactPhone,
      maintenanceMethod: record.maintenanceMethod,
      replacementParts: record.replacementParts,
      completionDate: record.completionDate,
      confirmer: record.confirmer,
      attachments: record.attachments
    })

  }

  // 保存编辑的维修记录
  const saveEditRecord = () => {
    if (!editingRepairData.systemName || !editingRepairData.equipmentName) {
      alert('请填写系统名称和设备名称')
      return
    }

    setRepairRecords(prev => 
      prev.map(record => 
        record.id === editingRepairRecordId 
          ? { ...editingRepairData, updateTime: new Date().toLocaleString() }
          : record
      )
    )
    setEditingRepairRecordId(null)
    setEditingRepairData({})
    // 维修记录修改成功
  }

  // 取消编辑
  const cancelEdit = () => {
    setEditingRepairRecordId(null)
    setEditingRepairData({})
  }

  // 维保记录表管理函数
  const resetMaintenanceForm = () => {
    setMaintenanceFormData({
      systemName: '',
      equipments: []
    })
  }

  const saveMaintenanceTable = async () => {
    if (!maintenanceFormData.systemName.trim()) {
      alert('请填写系统名称')
      return
    }

    try {
      // 将前端的equipments数据结构转换为后端期望的MaintenanceItem格式
      const maintenanceItems = []
      
      maintenanceFormData.equipments.forEach(equipment => {
        equipment.maintenanceItems.forEach(item => {
          const maintenanceItem = {
            system_name: maintenanceFormData.systemName,
            system_category: selectedSystem,
            equipment_name: equipment.name,
            content: item.content || '',
            level: item.level || '',
            cycle: item.cycle || '',
            type: item.type || '',
            // 直接传递months对象给后端
            months: item.months || {
              '1月': '', '2月': '', '3月': '', '4月': '', '5月': '', '6月': '',
              '7月': '', '8月': '', '9月': '', '10月': '', '11月': '', '12月': ''
            }
          }
          maintenanceItems.push(maintenanceItem)
        })
      })

      if (maintenanceItems.length === 0) {
        alert('请至少添加一个维保项目')
        return
      }

      if (editingMaintenanceId) {
        // 编辑模式：先删除原有数据，再创建新数据
        // 找到要编辑的记录
        const recordToEdit = maintenanceTableRecords.find(record => record.id === editingMaintenanceId)
        if (recordToEdit) {
          const systemNameToEdit = recordToEdit.systemName
          
          // 获取所有分页数据中相同系统名称的记录并删除
          let allItemsToDelete = []
          let nextUrl = '/equipment-maintenance/maintenance-items/'
          
          while (nextUrl) {
            const data = await equipmentMaintenanceAPI.maintenanceItems.getAll(nextUrl)
            
            // 筛选出需要删除的记录
            const itemsInThisPage = data.results.filter(item => 
              item.system_name === systemNameToEdit
            )
            allItemsToDelete = allItemsToDelete.concat(itemsInThisPage)
            
            // 检查是否有下一页，提取相对路径
            if (data.next && typeof data.next === 'string') {
              try {
                const url = new URL(data.next)
                // 移除 /api 前缀，只保留相对路径
                nextUrl = url.pathname.replace('/api', '') + url.search
              } catch (error) {
                console.error('Invalid URL:', data.next, error)
                nextUrl = null
              }
            } else {
              nextUrl = null
            }
          }
          
          // 批量删除原有数据
          if (allItemsToDelete.length > 0) {
            const deletePromises = allItemsToDelete.map(async (item) => {
              await equipmentMaintenanceAPI.maintenanceItems.delete(item.id)
            })
            await Promise.all(deletePromises)
          }
        }
        
        // 创建新数据
        const result = await equipmentMaintenanceAPI.maintenanceItems.batchCreate(maintenanceItems)
        // 维保记录表修改成功
      } else {
        // 新建模式：直接创建
        const result = await equipmentMaintenanceAPI.maintenanceItems.batchCreate(maintenanceItems)
        // 维保记录表保存成功
      }
      
      // 刷新本地数据
      await loadMaintenanceRecords()
      
      setShowMaintenanceForm(false)
      setEditingMaintenanceId(null)
      resetMaintenanceForm()
    } catch (error) {
      console.error('保存维保记录表失败:', error)
      alert(`保存失败: ${error.message}`)
    }
  }

  const deleteMaintenanceTable = async (recordId) => {
    if (window.confirm('确定要删除这个维保记录表吗？')) {
      try {
        // 找到要删除的记录
        const recordToDelete = maintenanceTableRecords.find(record => record.id === recordId)
        if (!recordToDelete) {
          alert('未找到要删除的记录')
          return
        }
        
        // 获取该记录的系统名称
        const systemNameToDelete = recordToDelete.systemName
        console.log('准备删除系统:', systemNameToDelete)
        
        // 获取所有分页数据中相同系统名称的记录
        let allItemsToDelete = []
        let nextUrl = '/equipment-maintenance/maintenance-items/'
        
        while (nextUrl) {
          const data = await equipmentMaintenanceAPI.maintenanceItems.getAll(nextUrl)
          console.log('获取到分页数据:', data)
          
          // 筛选出需要删除的记录
          const itemsInThisPage = data.results.filter(item => 
            item.system_name === systemNameToDelete
          )
          allItemsToDelete = allItemsToDelete.concat(itemsInThisPage)
          
          // 检查是否有下一页，提取相对路径
          if (data.next && typeof data.next === 'string') {
            try {
              const url = new URL(data.next)
              // 移除 /api 前缀，只保留相对路径
              nextUrl = url.pathname.replace('/api', '') + url.search
            } catch (error) {
              console.error('Invalid URL:', data.next, error)
              nextUrl = null
            }
          } else {
            nextUrl = null
          }
        }
        
        console.log('找到需要删除的所有记录:', allItemsToDelete)
        
        // 批量删除后端数据
        if (allItemsToDelete.length > 0) {
          const deletePromises = allItemsToDelete.map(async (item) => {
            console.log(`正在删除记录 ID: ${item.id}`)
            await equipmentMaintenanceAPI.maintenanceItems.delete(item.id)
            console.log(`成功删除记录 ID: ${item.id}`)
          })
          
          await Promise.all(deletePromises)
          console.log('所有删除操作完成')
        }
        
        // 重新加载数据以确保前端状态与后端同步
        await loadMaintenanceRecords()
        
        // 已删除维保记录表
      } catch (error) {
        console.error('删除维保记录表失败:', error)
        alert(`删除失败: ${error.message}`)
      }
    }
  }

  // 设备管理函数
  const addEquipment = () => {
    const newEquipment = {
      id: Date.now(),
      name: '新设备',
      maintenanceItems: []
    }
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: [...prev.equipments, newEquipment]
    }))
  }

  const deleteEquipment = (equipmentId) => {
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: prev.equipments.filter(eq => eq.id !== equipmentId)
    }))
    setContextMenu({ visible: false, x: 0, y: 0, type: '', equipmentId: null })
  }

  const updateEquipmentName = (equipmentId, newName) => {
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: prev.equipments.map(eq => 
        eq.id === equipmentId ? { ...eq, name: newName } : eq
      )
    }))
  }

  // 维保内容管理函数
  const addMaintenanceItem = (equipmentId) => {
    const newMaintenanceItem = {
      id: Date.now(),
      content: '新维保内容',
      level: '',
      cycle: '',
      type: '',
      months: {
        '1月': '', '2月': '', '3月': '', '4月': '', '5月': '', '6月': '',
        '7月': '', '8月': '', '9月': '', '10月': '', '11月': '', '12月': ''
      }
    }
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: prev.equipments.map(eq => 
        eq.id === equipmentId 
          ? { ...eq, maintenanceItems: [...eq.maintenanceItems, newMaintenanceItem] }
          : eq
      )
    }))
    setContextMenu({ visible: false, x: 0, y: 0, type: '', equipmentId: null })
  }

  const deleteMaintenanceItem = (equipmentId, maintenanceId) => {
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: prev.equipments.map(eq => 
        eq.id === equipmentId 
          ? { ...eq, maintenanceItems: eq.maintenanceItems.filter(item => item.id !== maintenanceId) }
          : eq
      )
    }))
  }

  const updateMaintenanceItem = (equipmentId, maintenanceId, field, value) => {
    setMaintenanceFormData(prev => ({
      ...prev,
      equipments: prev.equipments.map(eq => 
        eq.id === equipmentId 
          ? {
              ...eq,
              maintenanceItems: eq.maintenanceItems.map(item => 
                item.id === maintenanceId 
                  ? field.startsWith('month_') 
                    ? { ...item, months: { ...item.months, [field.replace('month_', '')]: value } }
                    : { ...item, [field]: value }
                  : item
              )
            }
          : eq
      )
    }))
  }

  // 右键菜单处理
  const handleContextMenu = (e, type, equipmentId = null, maintenanceId = null) => {
    e.preventDefault()
    setContextMenu({
      visible: true,
      x: e.clientX,
      y: e.clientY,
      type,
      equipmentId,
      maintenanceId
    })
  }

  const hideContextMenu = () => {
    setContextMenu({ visible: false, x: 0, y: 0, type: '', equipmentId: null, maintenanceId: null })
  }

  const startEditMaintenanceTable = (record) => {
    setMaintenanceFormData({
      systemName: record.systemName,
      equipments: record.equipments || []
    })
    setEditingMaintenanceId(record.id)
    setShowMaintenanceForm(true)
  }
  // 主界面
  const renderMainView = () => (
    <div className="card">
      <h2 style={{ marginBottom: '32px', textAlign: 'center' }}>设备维护管理</h2>
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        gap: '32px',
        flexWrap: 'wrap'
      }}>
        <div 
          onClick={() => setCurrentView('maintenance')}
          style={{
            width: '200px',
            height: '120px',
            border: '2px solid #3498db',
            borderRadius: '12px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            background: 'white',
            transition: 'all 0.3s ease',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}
          onMouseEnter={(e) => {
            e.target.style.background = '#f8f9fa'
            e.target.style.transform = 'translateY(-2px)'
          }}
          onMouseLeave={(e) => {
            e.target.style.background = 'white'
            e.target.style.transform = 'translateY(0)'
          }}
        >
          <Calendar size={32} color="#3498db" style={{ marginBottom: '8px' }} />
          <span style={{ fontSize: '16px', fontWeight: '600', color: '#333' }}>设备维护维保记录表</span>
        </div>

        <div 
          onClick={() => setCurrentView('repair')}
          style={{
            width: '200px',
            height: '120px',
            border: '2px solid #e74c3c',
            borderRadius: '12px',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer',
            background: 'white',
            transition: 'all 0.3s ease',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}
          onMouseEnter={(e) => {
            e.target.style.background = '#f8f9fa'
            e.target.style.transform = 'translateY(-2px)'
          }}
          onMouseLeave={(e) => {
            e.target.style.background = 'white'
            e.target.style.transform = 'translateY(0)'
          }}
        >
          <FileText size={32} color="#e74c3c" style={{ marginBottom: '8px' }} />
          <span style={{ fontSize: '16px', fontWeight: '600', color: '#333' }}>设备维修记录单</span>
        </div>
      </div>
    </div>
  )

  // 导出维修记录单到Word
  const exportRepairRecordToWord = async (record) => {
    try {
      // 调用后端API导出Word文档
      const response = await equipmentMaintenanceAPI.repairRecords.exportWord(record.id)
      
      // 创建下载链接
      const blob = new Blob([response], { 
        type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
      })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      
      const today = new Date()
      const dateStr = today.getFullYear() + 
        String(today.getMonth() + 1).padStart(2, '0') + 
        String(today.getDate()).padStart(2, '0')
      
      const fileName = `设备维修记录单_${record.recordNumber}_${dateStr}.docx`
      link.setAttribute('download', fileName)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
      
      // 维修记录单导出成功
    } catch (error) {
      console.error('导出Word文档失败:', error)
      alert('导出失败，请重试')
    }
  }

  // 组件初始化时加载数据
  useEffect(() => {
    loadMaintenanceRecords()
    loadRepairRecords()
  }, [])

  // 维修记录单界面
  const renderRepairView = () => {
    // 过滤搜索结果
    const filteredRepairRecords = repairRecords.filter(record => 
      record.systemName?.toLowerCase().includes(repairFormData.systemName?.toLowerCase() || '') ||
      record.equipmentName?.toLowerCase().includes(repairFormData.equipmentName?.toLowerCase() || '')
    )

    return (
      <div style={{ padding: '20px' }}>
        <div style={{ position: 'relative', marginBottom: '20px' }}>
          <button 
            onClick={() => setCurrentView('main')}
            style={{
              position: 'absolute',
              left: '0',
              top: '50%',
              transform: 'translateY(-50%)',
              padding: '8px 16px',
              backgroundColor: '#f0f0f0',
              border: '1px solid #ddd',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            ← 返回
          </button>
          <h2 style={{ margin: 0, color: '#333', textAlign: 'center' }}>设备维修记录单</h2>
        </div>

        {/* 操作栏 */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          gap: '16px',
          marginBottom: '20px',
          padding: '16px',
          backgroundColor: '#f8f9fa',
          borderRadius: '4px',
          border: '1px solid #e9ecef'
        }}>
          <span style={{ color: '#666', fontSize: '14px' }}>
            共 {repairRecords.length} 个记录单
          </span>

          <input
            type="file"
            accept=".doc,.docx"
            onChange={handleWordImport}
            style={{ display: 'none' }}
            id="word-import-input"
          />
          <button
            onClick={() => document.getElementById('word-import-input').click()}
            style={{
              padding: '8px 16px',
              backgroundColor: '#2196F3',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 'bold'
            }}
          >
            📥 导入Word
          </button>
          
          <button
            onClick={handleCreateNewRecord}
            style={{
              padding: '8px 16px',
              backgroundColor: '#4CAF50',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 'bold',
              marginLeft: '8px'
            }}
          >
            ➕ 新建记录
          </button>
        </div>

        {/* 新建记录表单 */}
        {showNewRecordForm && (
          <div style={{
            backgroundColor: 'white',
            border: '2px solid #4CAF50',
            borderRadius: '8px',
            padding: '20px',
            marginBottom: '20px'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' }}>
              <h3 style={{ margin: 0, color: '#4CAF50' }}>新建设备维修记录单</h3>
              <button 
                onClick={() => {
                  setShowNewRecordForm(false)
                  resetRepairForm()
                }}
                style={{
                  padding: '8px 16px',
                  backgroundColor: '#f44336',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer'
                }}
              >
                ✕ 关闭
              </button>
            </div>
            
            {/* 维修记录表单 */}
            <div style={{
              border: '2px solid #333',
              borderRadius: '4px',
              backgroundColor: 'white'
            }}>
              {/* 表头 */}
              <div style={{
                textAlign: 'center',
                fontSize: '18px',
                fontWeight: 'bold',
                padding: '16px',
                borderBottom: '1px solid #333',
                backgroundColor: '#f5f5f5',
                position: 'relative'
              }}>
                设备维修记录单
                <div style={{ position: 'absolute', right: '16px', top: '16px', fontSize: '14px' }}>
                  No: 
                  <input
                    type="text"
                    value={repairFormData.recordNumber}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, recordNumber: e.target.value }))}
                    style={{ 
                      border: 'none', 
                      background: 'transparent', 
                      fontSize: '14px',
                      width: '120px',
                      height: '32px',
                      borderBottom: '1px solid #ccc'
                    }}
                    placeholder="请填写编号"
                  />
                </div>
              </div>
              
              {/* 第一行 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>系统名称：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.systemName}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, systemName: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写系统名称"
                  />
                </div>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>设备名称：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.equipmentName}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, equipmentName: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写设备名称"
                  />
                </div>
              </div>
              
              {/* 第二行 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>故障日期：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="date"
                    value={repairFormData.faultDate}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, faultDate: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                  />
                </div>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>设备编号：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.equipmentNumber}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, equipmentNumber: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写设备编号"
                  />
                </div>
              </div>
              
              {/* 故障描述 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '15%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>故障描述：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                  <textarea
                    value={repairFormData.faultDescription}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, faultDescription: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                    placeholder="请描述故障情况"
                  />
                </div>
              </div>
              
              {/* 第三行 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>维修人员：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.maintainerName}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, maintainerName: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写维修人员"
                  />
                </div>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>联系方式：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.contactPhone}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, contactPhone: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写联系方式"
                  />
                </div>
              </div>
              
              {/* 维修方法 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '15%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>维修方法：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                  <textarea
                    value={repairFormData.maintenanceMethod}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, maintenanceMethod: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                    placeholder="请描述维修方法"
                  />
                </div>
              </div>
              
              {/* 更换备件 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '15%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>更换备件：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                  <textarea
                    value={repairFormData.replacementParts}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, replacementParts: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                    placeholder="请填写更换的备件信息"
                  />
                </div>
              </div>
              
              {/* 第四行 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>完成日期：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="date"
                    value={repairFormData.completionDate}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, completionDate: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                  />
                </div>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '25%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>确认人：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                  <input
                    type="text"
                    value={repairFormData.confirmer}
                    onChange={(e) => setRepairFormData(prev => ({ ...prev, confirmer: e.target.value }))}
                    style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                    placeholder="请填写确认人"
                  />
                </div>
              </div>
              
              {/* 附件 */}
              <div style={{ display: 'flex' }}>
                <div style={{
                  border: '1px solid #333',
                  padding: '8px',
                  width: '15%',
                  backgroundColor: '#f5f5f5',
                  fontWeight: 'bold'
                }}>附件：</div>
                <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                  <ImageUpload 
                    repairRecordId={repairFormData.id}
                    allowTempUpload={true}
                    onImagesChange={(images) => {
                      // 更新附件信息
                      const imageNames = images.map(img => img.name || img.file_name).join(', ')
                      setRepairFormData(prev => ({ ...prev, attachments: imageNames }))
                    }}
                    ref={imageUploadRef}
                  />
                  {repairFormData.attachments && (
                    <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
                      已上传: {repairFormData.attachments}
                    </div>
                  )}
                </div>
              </div>
            </div>
            
            {/* 操作按钮 */}
            <div style={{ display: 'flex', gap: '10px', marginTop: '20px', justifyContent: 'center' }}>
              <button 
                onClick={() => {
                  resetRepairForm()
                  const newRecordNumber = generateRecordNumber()
                  setRepairFormData(prev => ({ ...prev, recordNumber: newRecordNumber }))
                }}
                style={{
                  padding: '10px 20px',
                  backgroundColor: '#ff9800',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '14px'
                }}
              >
                🔄 重置表单
              </button>
              <button 
                onClick={saveRepairRecord}
                style={{
                  padding: '10px 20px',
                  backgroundColor: '#4CAF50',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: 'bold'
                }}
              >
                💾 保存记录
              </button>
            </div>
          </div>
        )}

        {/* 历史记录列表 */}
        {repairRecords.length > 0 && (
          <div style={{
            backgroundColor: 'white',
            border: '1px solid #ddd',
            borderRadius: '8px',
            padding: '20px'
          }}>
            <h3 style={{ margin: '0 0 20px 0', color: '#333' }}>历史维修记录单</h3>
            <div style={{
              maxHeight: '600px',
              overflowY: 'auto'
            }} className="repair-history-scroll">
              {repairRecords.slice().reverse().map((record, index) => (
                <div key={record.id} style={{
                  border: '1px solid #e0e0e0',
                  borderRadius: '6px',
                  padding: '16px',
                  marginBottom: '16px',
                  backgroundColor: '#fafafa'
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                    <div>
                      <div style={{ fontSize: '16px', color: '#333', fontWeight: 'bold' }}>
                        <strong>系统：</strong>{record.systemName}
                      </div>
                      <div style={{ fontSize: '16px', color: '#333', marginTop: '4px' }}>
                        <strong>设备：</strong>{record.equipmentName}
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button 
                        onClick={() => setViewingRecordId(viewingRecordId === record.id ? null : record.id)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: viewingRecordId === record.id ? '#ff9800' : '#9c27b0',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        👁️ {viewingRecordId === record.id ? '隐藏' : '查看'}
                      </button>
                      <button 
                        onClick={() => startEditRecord(record)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#2196f3',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        ✏️ 签署
                      </button>
                      <button 
                        onClick={() => exportRepairRecordToWord(record)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#4CAF50',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        📄 导出Word
                      </button>
                      <button 
                        onClick={() => deleteRepairRecord(record.id)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#f44336',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        🗑️ 删除
                      </button>
                    </div>
                  </div>

                  
                  {/* 设备维修记录单表格显示 */}
                  {viewingRecordId === record.id && (
                    <div style={{
                      marginTop: '16px',
                      border: '2px solid #333',
                      borderRadius: '8px',
                      backgroundColor: 'white',
                      fontFamily: 'SimSun, serif'
                    }}>
                      <div style={{
                        textAlign: 'center',
                        fontSize: '18px',
                        fontWeight: 'bold',
                        padding: '16px',
                        borderBottom: '1px solid #333',
                        backgroundColor: '#f5f5f5',
                        position: 'relative'
                      }}>
                        设备维修记录单
                        <div style={{ position: 'absolute', right: '16px', top: '16px', fontSize: '14px' }}>
                          No: {record.recordNumber || '未填写'}
                        </div>
                      </div>
                      
                      {/* 第一行 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>系统名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.systemName || '未填写'}
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>设备名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.equipmentName || '未填写'}
                        </div>
                      </div>
                      
                      {/* 第二行 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>故障日期</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.faultDate || '未填写'}
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>设备编号</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.equipmentNumber || '未填写'}
                        </div>
                      </div>
                      
                      {/* 故障描述 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>故障描述：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%', minHeight: '80px' }}>
                          {record.faultDescription || '未填写'}
                        </div>
                      </div>
                      
                      {/* 维修厂家信息 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>维修厂家名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.maintainerName || '未填写'}
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>厂家联系人及电话</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.contactPhone || '未填写'}
                        </div>
                      </div>
                      
                      {/* 维修方法 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>维修方法：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%', minHeight: '80px' }}>
                          {record.maintenanceMethod || '未填写'}
                        </div>
                      </div>
                      
                      {/* 更换备件 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>更换备件：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%', minHeight: '60px' }}>
                          {record.replacementParts || '未填写'}
                        </div>
                      </div>
                      
                      {/* 完成日期和确认人 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>完成日期</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.completionDate || '未填写'}
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>确认人</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          {record.confirmer || '未填写'}
                        </div>
                      </div>
                      
                      {/* 附图 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>附图：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%', minHeight: '60px' }}>
                          <ImageUpload 
                            repairRecordId={record.id}
                            readOnly={true}
                            onImagesChange={(images) => {
                              setRepairRecordImages(prev => ({
                                ...prev,
                                [record.id]: images
                              }))
                            }}
                          />
                        </div>
                      </div>
                    </div>
                  )}
                  
                  {/* 设备维修记录单编辑表单 */}
                  {editingRepairRecordId === record.id && (
                    <div style={{
                      marginTop: '16px',
                      border: '2px solid #333',
                      borderRadius: '8px',
                      backgroundColor: 'white',
                      fontFamily: 'SimSun, serif'
                    }}>
                      <div style={{
                        textAlign: 'center',
                        fontSize: '18px',
                        fontWeight: 'bold',
                        padding: '16px',
                        borderBottom: '1px solid #333',
                        backgroundColor: '#f5f5f5',
                        position: 'relative'
                      }}>
                        签署设备维修记录单
                        <div style={{ position: 'absolute', right: '16px', top: '16px', fontSize: '14px' }}>
                          No: 
                          <input
                            type="text"
                            value={repairFormData.recordNumber}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, recordNumber: e.target.value }))}
                            style={{ 
                              border: 'none', 
                              background: 'transparent', 
                              fontSize: '14px',
                              width: '120px',
                              height: '32px',
                              borderBottom: '1px solid #ccc'
                            }}
                            placeholder="请填写编号"
                          />
                        </div>
                      </div>
                      
                      {/* 第一行 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>系统名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.systemName}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, systemName: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写系统名称"
                          />
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>设备名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.equipmentName}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, equipmentName: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写设备名称"
                          />
                        </div>
                      </div>
                      
                      {/* 第二行 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>故障日期</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="date"
                            value={repairFormData.faultDate}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, faultDate: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                          />
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>设备编号</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.equipmentNumber}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, equipmentNumber: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写设备编号"
                          />
                        </div>
                      </div>
                      
                      {/* 故障描述 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>故障描述：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                          <textarea
                            value={repairFormData.faultDescription}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, faultDescription: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                            placeholder="请描述故障情况"
                          />
                        </div>
                      </div>
                      
                      {/* 维修厂家信息 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>维修厂家名称</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.maintainerName}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, maintainerName: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写维修厂家"
                          />
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>厂家联系人及电话</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.contactPhone}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, contactPhone: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写联系方式"
                          />
                        </div>
                      </div>
                      
                      {/* 维修方法 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>维修方法：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                          <textarea
                            value={repairFormData.maintenanceMethod}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, maintenanceMethod: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                            placeholder="请描述维修方法"
                          />
                        </div>
                      </div>
                      
                      {/* 更换备件 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>更换备件：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                          <textarea
                            value={repairFormData.replacementParts}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, replacementParts: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', minHeight: '80px', resize: 'vertical' }}
                            placeholder="请填写更换的备件信息"
                          />
                        </div>
                      </div>
                      
                      {/* 完成日期和确认人 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>完成日期</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="date"
                            value={repairFormData.completionDate}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, completionDate: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                          />
                        </div>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '25%',
                          backgroundColor: '#f5f5f5',
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>确认人</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '25%' }}>
                          <input
                            type="text"
                            value={repairFormData.confirmer}
                            onChange={(e) => setRepairFormData(prev => ({ ...prev, confirmer: e.target.value }))}
                            style={{ width: '100%', border: 'none', background: 'transparent', height: '36px' }}
                            placeholder="请填写确认人"
                          />
                        </div>
                      </div>
                      
                      {/* 附图 */}
                      <div style={{ display: 'flex' }}>
                        <div style={{
                          border: '1px solid #333',
                          padding: '8px',
                          width: '15%',
                          backgroundColor: '#f5f5f5',
                          fontWeight: 'bold'
                        }}>附图：</div>
                        <div style={{ border: '1px solid #333', padding: '8px', width: '85%' }}>
                          <ImageUpload 
                            repairRecordId={editingRepairRecordId || (repairFormData.id ? repairFormData.id : null)}
                            onImagesChange={(images) => {
                              const recordId = editingRepairRecordId || repairFormData.id
                              if (recordId) {
                                setRepairRecordImages(prev => ({
                                  ...prev,
                                  [recordId]: images
                                }))
                              }
                            }}
                          />
                        </div>
                      </div>
                      
                      {/* 操作按钮 */}
                      <div style={{ display: 'flex', gap: '12px', margin: '20px', justifyContent: 'center' }}>
                        <button 
                          onClick={resetRepairForm}
                          style={{
                            padding: '10px 20px',
                            backgroundColor: '#ff9800',
                            color: 'white',
                            border: 'none',
                            borderRadius: '4px',
                            cursor: 'pointer',
                            fontSize: '14px'
                          }}
                        >
                          🔄 重置表单
                        </button>
                        <button 
                           onClick={saveRepairRecord}
                           style={{
                             padding: '10px 20px',
                             backgroundColor: '#4CAF50',
                             color: 'white',
                             border: 'none',
                             borderRadius: '4px',
                             cursor: 'pointer',
                             fontSize: '14px',
                             fontWeight: 'bold'
                           }}
                         >
                           💾 保存签署
                         </button>
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {repairRecords.length === 0 && (
          <div style={{
            textAlign: 'center',
            padding: '40px',
            color: '#666',
            backgroundColor: '#f9f9f9',
            borderRadius: '8px',
            border: '1px solid #e0e0e0'
          }}>
            <p>暂无维修记录单，点击"新建记录单"开始创建</p>
          </div>
        )}
      </div>
    )
  }
  
  // 维保记录表界面
  const renderMaintenanceView = () => {
    // 根据分类过滤维保记录，而不是根据系统名称
    const filteredMaintenanceRecords = maintenanceTableRecords.filter(record => 
      record.systemCategory === selectedSystem
    )

    // 渲染维保记录表单
    const renderMaintenanceForm = () => (
      <div style={{
        backgroundColor: 'white',
        border: '2px solid #2196f3',
        borderRadius: '8px',
        padding: '20px',
        marginBottom: '20px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '20px' }}>
          <h3 style={{ margin: 0, color: '#1976d2' }}>
            {editingMaintenanceId ? '签署系统维护保养记录表' : '新建系统维护保养记录表'}
          </h3>
          <button 
            onClick={() => {
              setShowMaintenanceForm(false)
              setEditingMaintenanceId(null)
              resetMaintenanceForm()
            }}
            style={{
              padding: '8px 16px',
              backgroundColor: '#f44336',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            ✕ 关闭
          </button>
        </div>

        {/* 系统名称输入 */}
        <div style={{ marginBottom: '20px' }}>
          <label style={{ display: 'block', marginBottom: '8px', fontWeight: 'bold', color: '#333' }}>
            系统名称：<span style={{ color: 'red' }}>*</span>
          </label>
          <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
            <input
              type="text"
              value={maintenanceFormData.systemName}
              onChange={(e) => setMaintenanceFormData(prev => ({ ...prev, systemName: e.target.value }))}
              placeholder="请输入系统名称"
              style={{
                width: '300px',
                padding: '10px',
                border: '1px solid #ddd',
                borderRadius: '4px',
                fontSize: '14px'
              }}
            />
            <button
              onClick={addEquipment}
              style={{
                padding: '10px 16px',
                backgroundColor: '#2196f3',
                color: 'white',
                border: 'none',
                borderRadius: '4px',
                cursor: 'pointer',
                fontSize: '14px',
                fontWeight: 'bold',
                display: 'flex',
                alignItems: 'center',
                gap: '6px'
              }}
            >
              ➕ 新建设备
            </button>
          </div>
        </div>

        {/* 维保记录表格 - 新的树形结构 */}
        <div style={{ 
          overflowX: 'auto',
          border: '2px solid #333',
          borderRadius: '4px',
          backgroundColor: 'white',
          marginBottom: '20px',
          position: 'relative'
        }}>
          <table style={{ 
            width: '100%', 
            minWidth: '1200px',
            borderCollapse: 'collapse',
            fontSize: '14px'
          }}>
            <thead>
              <tr style={{ backgroundColor: '#f5f5f5' }}>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '50px'
                }}>序号</th>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '120px'
                }}>设备名称</th>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '150px'
                }}>维保内容</th>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '80px'
                }}>维保等级</th>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '80px'
                }}>维保周期</th>
                <th rowSpan={2} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold',
                  width: '80px'
                }}>维保类型</th>
                <th colSpan={12} style={{ 
                  border: '1px solid #333', 
                  padding: '12px 8px', 
                  textAlign: 'center',
                  fontWeight: 'bold'
                }}>月份</th>
              </tr>
              <tr style={{ backgroundColor: '#f5f5f5' }}>
                {['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'].map(month => (
                  <th key={month} style={{ 
                    border: '1px solid #333', 
                    padding: '8px', 
                    textAlign: 'center',
                    fontWeight: 'bold',
                    width: '60px'
                  }}>{month}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {maintenanceFormData.equipments.length === 0 ? (
                <tr>
                  <td colSpan={18} style={{
                    border: '1px solid #333',
                    padding: '40px',
                    textAlign: 'center',
                    color: '#666',
                    backgroundColor: '#f9f9f9'
                  }}>
                    暂无设备，右键空白区域添加设备
                  </td>
                </tr>
              ) : (
                maintenanceFormData.equipments.map((equipment, equipmentIndex) => {
                  // 如果设备没有维保内容，显示一行提示
                  if (equipment.maintenanceItems.length === 0) {
                    return (
                      <tr 
                        key={equipment.id}
                        onContextMenu={(e) => handleContextMenu(e, 'equipment', equipment.id)}
                        style={{ backgroundColor: '#e3f2fd', cursor: 'context-menu' }}
                      >
                        <td style={{ 
                          border: '1px solid #333', 
                          padding: '8px', 
                          textAlign: 'center',
                          fontWeight: 'bold'
                        }}>{equipmentIndex + 1}</td>
                        <td style={{ 
                          border: '1px solid #333', 
                          padding: '8px',
                          fontWeight: 'bold'
                        }}>
                          <input
                            type="text"
                            value={equipment.name}
                            onChange={(e) => updateEquipmentName(equipment.id, e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '4px',
                              fontSize: '14px',
                              backgroundColor: 'transparent',
                              fontWeight: 'bold'
                            }}
                          />
                        </td>
                        <td colSpan={16} style={{ 
                          border: '1px solid #333', 
                          padding: '8px',
                          color: '#666',
                          fontStyle: 'italic'
                        }}>
                          右键添加维保内容
                        </td>
                      </tr>
                    )
                  }
                  
                  // 如果设备有维保内容，使用合并单元格显示
                  return equipment.maintenanceItems.map((item, itemIndex) => (
                    <tr 
                      key={item.id}
                    >
                      {/* 序号列 - 只在第一行显示 */}
                      {itemIndex === 0 && (
                        <td 
                          rowSpan={equipment.maintenanceItems.length}
                          style={{ 
                            border: '1px solid #333', 
                            padding: '8px', 
                            textAlign: 'center',
                            fontWeight: 'bold',
                            backgroundColor: '#e3f2fd',
                            verticalAlign: 'middle'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'equipment', equipment.id)}
                        >
                          {equipmentIndex + 1}
                        </td>
                      )}
                      {/* 设备名称列 - 只在第一行显示 */}
                      {itemIndex === 0 && (
                        <td 
                          rowSpan={equipment.maintenanceItems.length}
                          style={{ 
                            border: '1px solid #333', 
                            padding: '8px',
                            fontWeight: 'bold',
                            backgroundColor: '#e3f2fd',
                            verticalAlign: 'middle'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'equipment', equipment.id)}
                        >
                          <input
                            type="text"
                            value={equipment.name}
                            onChange={(e) => updateEquipmentName(equipment.id, e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '4px',
                              fontSize: '14px',
                              backgroundColor: 'transparent',
                              fontWeight: 'bold'
                            }}
                          />
                        </td>
                      )}
                        <td 
                          style={{ 
                            border: '1px solid #333', 
                            padding: '2px'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'maintenance', equipment.id, item.id)}
                        >
                          <input
                            type="text"
                            value={item.content}
                            onChange={(e) => updateMaintenanceItem(equipment.id, item.id, 'content', e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '6px',
                              fontSize: '12px',
                              backgroundColor: 'transparent'
                            }}
                          />
                        </td>
                        <td 
                          style={{ 
                            border: '1px solid #333', 
                            padding: '2px'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'maintenance', equipment.id, item.id)}
                        >
                          <input
                            type="text"
                            value={item.level}
                            onChange={(e) => updateMaintenanceItem(equipment.id, item.id, 'level', e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '6px',
                              fontSize: '12px',
                              backgroundColor: 'transparent'
                            }}
                          />
                        </td>
                        <td 
                          style={{ 
                            border: '1px solid #333', 
                            padding: '2px'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'maintenance', equipment.id, item.id)}
                        >
                          <input
                            type="text"
                            value={item.cycle}
                            onChange={(e) => updateMaintenanceItem(equipment.id, item.id, 'cycle', e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '6px',
                              fontSize: '12px',
                              backgroundColor: 'transparent'
                            }}
                          />
                        </td>
                        <td 
                          style={{ 
                            border: '1px solid #333', 
                            padding: '2px'
                          }}
                          onContextMenu={(e) => handleContextMenu(e, 'maintenance', equipment.id, item.id)}
                        >
                          <input
                            type="text"
                            value={item.type}
                            onChange={(e) => updateMaintenanceItem(equipment.id, item.id, 'type', e.target.value)}
                            style={{
                              width: '100%',
                              border: 'none',
                              padding: '6px',
                              fontSize: '12px',
                              backgroundColor: 'transparent'
                            }}
                          />
                        </td>
                        {['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'].map(month => (
                          <td 
                            key={month} 
                            style={{ 
                              border: '1px solid #333', 
                              padding: '2px',
                              textAlign: 'center',
                              cursor: 'pointer',
                              userSelect: 'none'
                            }}
                            onContextMenu={(e) => handleContextMenu(e, 'maintenance', equipment.id, item.id)}
                            onClick={() => {
                              const currentValue = item.months[month] || ''
                              const newValue = currentValue === '✓' ? '' : '✓'
                              updateMaintenanceItem(equipment.id, item.id, `month_${month}`, newValue)
                            }}
                          >
                            <div
                              style={{
                                width: '100%',
                                height: '100%',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                padding: '6px',
                                fontSize: '14px',
                                fontWeight: 'bold',
                                color: '#4CAF50'
                              }}
                            >  
                              {item.months[month] === '✓' ? '✓' : ''}
                            </div>
                          </td>
                        ))}
                      </tr>
                    ))
                  })
              )}
            </tbody>
          </table>
          

        </div>

        {/* 右键菜单 */}
        {contextMenu.visible && (
          <div
            style={{
              position: 'fixed',
              top: contextMenu.y,
              left: contextMenu.x,
              backgroundColor: 'white',
              border: '1px solid #ccc',
              borderRadius: '4px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.15)',
              zIndex: 1000,
              minWidth: '120px'
            }}
            onClick={hideContextMenu}
          >

            {contextMenu.type === 'equipment' && (
              <>
                <div
                  onClick={() => addMaintenanceItem(contextMenu.equipmentId)}
                  style={{
                    padding: '8px 12px',
                    cursor: 'pointer',
                    borderBottom: '1px solid #eee'
                  }}
                  onMouseEnter={(e) => e.target.style.backgroundColor = '#f5f5f5'}
                  onMouseLeave={(e) => e.target.style.backgroundColor = 'white'}
                >
                  ➕ 添加维保内容
                </div>
                <div
                  onClick={() => deleteEquipment(contextMenu.equipmentId)}
                  style={{
                    padding: '8px 12px',
                    cursor: 'pointer',
                    color: '#f44336'
                  }}
                  onMouseEnter={(e) => e.target.style.backgroundColor = '#f5f5f5'}
                  onMouseLeave={(e) => e.target.style.backgroundColor = 'white'}
                >
                  🗑️ 删除设备
                </div>
              </>
            )}
            {contextMenu.type === 'maintenance' && (
              <div
                onClick={() => deleteMaintenanceItem(contextMenu.equipmentId, contextMenu.maintenanceId)}
                style={{
                  padding: '8px 12px',
                  cursor: 'pointer',
                  color: '#f44336'
                }}
                onMouseEnter={(e) => e.target.style.backgroundColor = '#f5f5f5'}
                onMouseLeave={(e) => e.target.style.backgroundColor = 'white'}
              >
                🗑️ 删除维保内容
              </div>
            )}
          </div>
        )}

        {/* 操作按钮 */}
        <div style={{ display: 'flex', gap: '12px' }}>
          <button 
            onClick={resetMaintenanceForm}
            style={{
              padding: '10px 20px',
              backgroundColor: '#ff9800',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px'
            }}
          >
            🔄 重置表单
          </button>
          <button 
            onClick={saveMaintenanceTable}
            style={{
              padding: '10px 20px',
              backgroundColor: '#4CAF50',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: 'pointer',
              fontSize: '14px',
              fontWeight: 'bold'
            }}
          >
            💾 {editingMaintenanceId ? '保存签署' : '保存记录表'}
          </button>
        </div>
      </div>
    )

    return (
      <div style={{ padding: '20px' }}>
        <div style={{ position: 'relative', marginBottom: '20px' }}>
          <button 
            onClick={() => setCurrentView('main')}
            style={{
              position: 'absolute',
              left: '0',
              top: '50%',
              transform: 'translateY(-50%)',
              padding: '8px 16px',
              backgroundColor: '#f0f0f0',
              border: '1px solid #ddd',
              borderRadius: '4px',
              cursor: 'pointer'
            }}
          >
            ← 返回
          </button>
          <h2 style={{ margin: 0, color: '#333', textAlign: 'center' }}>设备维护维保记录表</h2>
        </div>

        {/* 系统分类选项卡 */}
        <div style={{
          backgroundColor: '#ffffff',
          borderRadius: '8px',
          border: '1px solid #e0e0e0',
          marginBottom: '20px',
          overflow: 'hidden'
        }}>
          {/* 选项卡头部 */}
          <div style={{
            display: 'flex',
            borderBottom: '1px solid #e0e0e0',
            backgroundColor: '#f8f9fa'
          }}>
            {[
              { name: '真空热试验系统维护保养记录表', shortName: '真空热试验', color: '#ff5722' },
              { name: '振动试验系统维护保养记录表', shortName: '振动试验', color: '#9c27b0' },
              { name: 'EMC试验系统维护保养记录表', shortName: 'EMC试验', color: '#3f51b5' },
              { name: '磁试验系统维护保养记录表', shortName: '磁试验', color: '#009688' },
              { name: '常压试验系统维护保养记录表', shortName: '常压试验', color: '#ff9800' }
            ].map((system, index) => (
              <div
                key={index}
                onClick={() => setSelectedSystem(system.name)}
                style={{
                  flex: 1,
                  padding: '16px 12px',
                  textAlign: 'center',
                  cursor: 'pointer',
                  backgroundColor: selectedSystem === system.name ? system.color : 'transparent',
                  color: selectedSystem === system.name ? 'white' : '#333',
                  fontWeight: selectedSystem === system.name ? 'bold' : 'normal',
                  fontSize: '14px',
                  transition: 'all 0.3s ease',
                  borderBottom: selectedSystem === system.name ? `3px solid ${system.color}` : '3px solid transparent',
                  position: 'relative'
                }}
                onMouseEnter={(e) => {
                  if (selectedSystem !== system.name) {
                    e.target.style.backgroundColor = '#f0f0f0'
                  }
                }}
                onMouseLeave={(e) => {
                  if (selectedSystem !== system.name) {
                    e.target.style.backgroundColor = 'transparent'
                  }
                }}
              >
                {system.shortName}
              </div>
            ))}
          </div>
          
          {/* 选项卡内容区域 */}
          <div style={{
            padding: '20px'
          }}>
            {/* 当前选中系统的操作按钮 */}
            <div style={{
              display: 'flex',
              justifyContent: 'center',
              gap: '16px',
              marginBottom: '20px'
            }}>
              <button 
                onClick={() => {
                  const input = document.createElement('input')
                  input.type = 'file'
                  input.accept = '.xlsx,.xls'
                  input.onchange = (e) => {
                    const file = e.target.files[0]
                    if (file) {
                      importMaintenanceTable(file, selectedSystem)
                    }
                  }
                  input.click()
                }}
                style={{
                  padding: '12px 24px',
                  backgroundColor: '#4CAF50',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: 'bold',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s ease'
                }}
                onMouseEnter={(e) => {
                  e.target.style.transform = 'translateY(-2px)'
                  e.target.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)'
                }}
                onMouseLeave={(e) => {
                  e.target.style.transform = 'translateY(0)'
                  e.target.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                📥 导入Excel文件
              </button>
              <button 
                onClick={() => {
                  setMaintenanceFormData({
                    systemName: '',
                    equipments: []
                  })
                  setShowMaintenanceForm(true)
                  setEditingMaintenanceId(null)
                }}
                style={{
                  padding: '12px 24px',
                  backgroundColor: '#2196F3',
                  color: 'white',
                  border: 'none',
                  borderRadius: '6px',
                  cursor: 'pointer',
                  fontSize: '14px',
                  fontWeight: 'bold',
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s ease'
                }}
                onMouseEnter={(e) => {
                  e.target.style.transform = 'translateY(-2px)'
                  e.target.style.boxShadow = '0 4px 8px rgba(0,0,0,0.2)'
                }}
                onMouseLeave={(e) => {
                  e.target.style.transform = 'translateY(0)'
                  e.target.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                ➕ 新建记录表
              </button>
            </div>
            

          </div>
        </div>



        {/* 表单区域 */}
        {showMaintenanceForm && renderMaintenanceForm()}

        {/* 历史记录列表 */}
        {filteredMaintenanceRecords.length > 0 && (
          <div style={{
            backgroundColor: 'white',
            border: '1px solid #ddd',
            borderRadius: '8px',
            padding: '20px'
          }}>
            <h3 style={{ margin: '0 0 20px 0', color: '#333' }}>{selectedSystem}</h3>
            <div style={{
              maxHeight: '600px',
              overflowY: 'auto',
              className: 'maintenance-history-scroll'
            }}>
              {filteredMaintenanceRecords.map((record, index) => (
                <div key={record.id} style={{
                  border: '1px solid #e0e0e0',
                  borderRadius: '6px',
                  padding: '16px',
                  marginBottom: '16px',
                  backgroundColor: '#fafafa'
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
                    <div>
                      <h4 style={{ margin: '0 0 4px 0', color: '#1976d2' }}>{record.systemName}</h4>
                      <div style={{ fontSize: '12px', color: '#666' }}>
                        创建时间：{record.createTime}
                        {record.updateTime && <span style={{ marginLeft: '16px' }}>修改时间：{record.updateTime}</span>}
                      </div>
                    </div>
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <button 
                        onClick={() => startEditMaintenanceTable(record)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#2196f3',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        ✏️ 签署
                      </button>
                      <button 
                        onClick={() => exportSpecificMaintenanceToExcel(record)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#4CAF50',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        📊 导出Excel
                      </button>
                      <button 
                        onClick={() => deleteMaintenanceTable(record.id)}
                        style={{
                          padding: '6px 12px',
                          backgroundColor: '#f44336',
                          color: 'white',
                          border: 'none',
                          borderRadius: '4px',
                          cursor: 'pointer',
                          fontSize: '12px'
                        }}
                      >
                        🗑️ 删除
                      </button>
                    </div>
                  </div>
                  
                  {/* 显示表格数据摘要 */}
                  <div style={{ fontSize: '14px', color: '#555' }}>
                    <strong>设备数量：</strong>{record.equipments?.length || 0} 个
                    <span style={{ marginLeft: '20px' }}>
                      <strong>维保内容总数：</strong>
                      {record.equipments?.reduce((total, eq) => total + (eq.maintenanceItems?.length || 0), 0) || 0} 项
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {filteredMaintenanceRecords.length === 0 && (
          <div style={{
            textAlign: 'center',
            padding: '40px',
            color: '#666',
            backgroundColor: '#f9f9f9',
            borderRadius: '8px',
            border: '1px solid #e0e0e0'
          }}>
            <p>暂无维保记录表，请选择上方对应系统按钮创建记录表</p>
          </div>
        )}
      </div>
    )
  }

  // 导入维保记录表Excel文件
  const importMaintenanceTable = async (file, systemCategory) => {
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        
        if (jsonData.length < 2) {
          alert('Excel文件格式不正确，至少需要包含表头和数据行')
          return
        }
        
        // 查找表头行（包含"设备名称"的行）
        let headerRowIndex = -1
        for (let i = 0; i < jsonData.length; i++) {
          const row = jsonData[i]
          if (row && row.some(cell => 
            cell && typeof cell === 'string' && 
            (cell.includes('设备名称') || cell.includes('维保内容') || cell.includes('维保等级'))
          )) {
            headerRowIndex = i
            break
          }
        }
        
        if (headerRowIndex === -1) {
          alert('未找到有效的表头行，请确保Excel文件包含"设备名称"、"维保内容"等列')
          return
        }
        
        const headers = jsonData[headerRowIndex]
        const dataRows = jsonData.slice(headerRowIndex + 1)
        
        // 解析列索引
        const getColumnIndex = (keywords) => {
          for (const keyword of keywords) {
            const index = headers.findIndex(header => 
              header && typeof header === 'string' && header.includes(keyword)
            )
            if (index !== -1) return index
          }
          return -1
        }
        
        const columnMapping = {
          序号: getColumnIndex(['序号', '编号']),
          设备名称: getColumnIndex(['设备名称', '设备名']),
          维保内容: getColumnIndex(['维保内容', '保养内容', '维护内容']),
          维保等级: getColumnIndex(['维保等级', '保养等级', '维护等级', '等级']),
          维保周期: getColumnIndex(['维保周期', '保养周期', '维护周期', '周期']),
          维保类型: getColumnIndex(['维保类型', '保养类型', '维护类型', '类型']),
        }
        
        // 查找月份列
        const monthColumns = {}
        for (let i = 1; i <= 12; i++) {
          const monthKey = `${i}月`
          monthColumns[monthKey] = getColumnIndex([monthKey, `${i}月`, `${String(i).padStart(2, '0')}月`])
        }
        
        // 检查必要列是否存在
        if (columnMapping.设备名称 === -1) {
          alert('Excel文件中缺少"设备名称"列，无法导入')
          return
        }
        
        // 解析数据
        const equipmentMap = new Map()
        let validRowCount = 0
        let currentEquipmentName = '' // 记录当前设备名称，用于处理合并单元格
        
        dataRows.forEach((row, index) => {
          if (!row || row.length === 0) return
          
          // 获取设备名称，如果当前行为空，则使用上一行的设备名称（处理合并单元格）
          let equipmentName = row[columnMapping.设备名称]
          if (equipmentName && typeof equipmentName === 'string' && equipmentName.trim() !== '') {
            currentEquipmentName = equipmentName.trim()
          } else if (currentEquipmentName) {
            equipmentName = currentEquipmentName
          } else {
            return // 没有设备名称，跳过
          }
          
          const maintenanceContent = row[columnMapping.维保内容] || ''
          const maintenanceLevel = row[columnMapping.维保等级] || ''
          const maintenanceCycle = row[columnMapping.维保周期] || ''
          const maintenanceType = row[columnMapping.维保类型] || ''
          
          // 如果没有维保内容，跳过这行
          if (!maintenanceContent.trim()) {
            return
          }
          
          // 解析月份数据
          const months = {}
          Object.keys(monthColumns).forEach(monthKey => {
            const columnIndex = monthColumns[monthKey]
            if (columnIndex !== -1 && row[columnIndex]) {
              months[monthKey] = row[columnIndex].toString().trim()
            }
          })
          
          // 创建维保项目
          const maintenanceItem = {
            id: Date.now() + Math.random(),
            content: maintenanceContent.trim(),
            level: maintenanceLevel.toString().trim(),
            cycle: maintenanceCycle.toString().trim(),
            type: maintenanceType.toString().trim(),
            months: months
          }
          
          // 添加到设备映射
          if (!equipmentMap.has(equipmentName)) {
            equipmentMap.set(equipmentName, {
              id: Date.now() + Math.random(),
              name: equipmentName,
              maintenanceItems: []
            })
          }
          
          equipmentMap.get(equipmentName).maintenanceItems.push(maintenanceItem)
          validRowCount++
        })
        
        if (validRowCount === 0) {
          alert('Excel文件中没有找到有效的维保记录数据')
          return
        }
        
        // 将导入的数据转换为后端API格式
        const maintenanceItems = []
        const systemName = systemCategory.replace('维护保养记录表', '')
        
        Array.from(equipmentMap.values()).forEach(equipment => {
          equipment.maintenanceItems.forEach(item => {
            const maintenanceItem = {
              system_name: systemName,
              system_category: systemCategory,
              equipment_name: equipment.name,
              content: item.content || '',
              level: item.level || '',
              cycle: item.cycle || '',
              type: item.type || '',
              // 直接传递months对象给后端
              months: item.months || {
                '1月': '', '2月': '', '3月': '', '4月': '', '5月': '', '6月': '',
                '7月': '', '8月': '', '9月': '', '10月': '', '11月': '', '12月': ''
              }
            }
            maintenanceItems.push(maintenanceItem)
          })
        })
        
        console.log('准备保存到后端的数据：', maintenanceItems)
        
        // 调用后端API批量创建维保记录
        try {
          const result = await equipmentMaintenanceAPI.maintenanceItems.batchCreate(maintenanceItems)
          
          // 导入成功后直接刷新数据，不显示提示
          
          // 刷新维保记录列表
          await loadMaintenanceRecords()
        } catch (apiError) {
          console.error('调用后端API失败:', apiError)
          alert(`导入失败: ${apiError.message}`)
        }
        
      } catch (error) {
        console.error('Excel文件解析错误:', error)
        alert('Excel文件解析失败，请检查文件格式是否正确')
      }
    }
    reader.readAsArrayBuffer(file)
  }

  // 导出特定维保记录表到Excel
  const exportSpecificMaintenanceToExcel = (record) => {
    const headers = [
      '序号', '设备名称', '维保内容', '维保等级', '维保周期', '维保类型',
      '1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'
    ]
    
    const rows = []
    let rowIndex = 1
    
    // 将equipments结构转换为平面表格数据
    if (record.equipments) {
      record.equipments.forEach(equipment => {
        if (equipment.maintenanceItems && equipment.maintenanceItems.length > 0) {
          equipment.maintenanceItems.forEach(item => {
            rows.push([
              rowIndex++,
              equipment.name || '',
              item.content || '',
              item.level || '',
              item.cycle || '',
              item.type || '',
              item.months?.['1月'] || '',
              item.months?.['2月'] || '',
              item.months?.['3月'] || '',
              item.months?.['4月'] || '',
              item.months?.['5月'] || '',
              item.months?.['6月'] || '',
              item.months?.['7月'] || '',
              item.months?.['8月'] || '',
              item.months?.['9月'] || '',
              item.months?.['10月'] || '',
              item.months?.['11月'] || '',
              item.months?.['12月'] || ''
            ])
          })
        } else {
          // 如果设备没有维保内容，也要显示设备名称
          rows.push([
            rowIndex++,
            equipment.name || '',
            '', '', '', '',
            '', '', '', '', '', '',
            '', '', '', '', '', ''
          ])
        }
      })
    }
    
    const csvContent = [headers, ...rows]
      .map(row => row.map(cell => `"${cell}"`).join(','))
      .join('\n')
    
    const BOM = '\uFEFF'
    const blob = new Blob([BOM + csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    
    const today = new Date()
    const dateStr = today.getFullYear() + 
      String(today.getMonth() + 1).padStart(2, '0') + 
      String(today.getDate()).padStart(2, '0')
    
    const systemName = record.systemName.replace(/[\\/:*?"<>|]/g, '_') // 替换文件名中的非法字符
    link.setAttribute('download', `${systemName}_维保记录表_${dateStr}.csv`)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    alert(`${record.systemName} 维保记录表导出成功！`)
  }



  // 根据当前视图渲染对应界面
  const renderCurrentView = () => {
    switch (currentView) {
      case 'maintenance':
        return renderMaintenanceView()
      case 'repair':
        return renderRepairView()
      default:
        return renderMainView()
    }
  }



  return renderCurrentView()
}

export default EquipmentMaintenance